<template>
  <view :style="{ width: coverDom.width + 'px', height: coverDom.width * (4 / 5) + 'px' }" class="cover">
    <canvas id="myCanvas" type="2d" style="width: 100%; height: 100%" />
  </view>
</template>
<script setup>
  import { ref, defineProps, watch, getCurrentInstance, nextTick, defineExpose } from 'vue';
  import { onLoad, onShow, onHide } from '@dcloudio/uni-app';
  import { uploadFn } from '@/common/js/fn';
  let props = defineProps({
    modelValue: {
      type: String,
      default: ''
    },
    coverDom: {
      type: Object,
      default: () => {
        return { width: 0, height: 0 };
      }
    },
    dragPosition: {
      type: Number,
      default: () => {
        return 0;
      }
    }
  });
  let ctx, canvasDraw, canvasEl, imageWidth;
  let instance = getCurrentInstance();
  const canvasInit = () => {
    const query = uni.createSelectorQuery().in(instance);
    uni.getImageInfo({
      src: props.modelValue,
      success: ({ width, path }) => {
        imageWidth = width;
        query
          .select('#myCanvas')
          .fields({ node: true, size: true })
          .exec(res => {
            // Canvas 对象
            canvasEl = res[0].node;
            // Canvas 画布的实际绘制宽高
            const renderWidth = res[0].width;
            const renderHeight = res[0].height;
            // Canvas 绘制上下文
            ctx = canvasEl.getContext('2d');
            const image = canvasEl.createImage();
            // 初始化画布大小
            const dpr = wx.getWindowInfo().pixelRatio;
            canvasEl.width = renderWidth * dpr;
            canvasEl.height = renderHeight * dpr;
            ctx.scale(dpr, dpr);
            image.src = path;
            image.onload = () => {
              canvasDraw = () => {
                // 清除花布
                ctx.clearRect(0, 0, canvasEl.width, canvasEl.height);
                // 绘画
                ctx.drawImage(
                  image,
                  0,
                  (props.dragPosition * (width * (4 / 5))) / (props.coverDom.width * (4 / 5)),
                  width,
                  width * (4 / 5),
                  0,
                  0,
                  props.coverDom.width,
                  props.coverDom.width * (4 / 5)
                );
              };
              canvasDraw();
            };
          });
      }
    });
  };
  watch(
    () => props.dragPosition,
    () => {
      if (ctx) canvasDraw();
    },
    { immediate: true }
  );
  watch(
    () => props.modelValue,
    val => {
      if (val) {
        canvasInit();
      }
    },
    { immediate: true }
  );
  // canvas 截图
  const extendCanvas = () => {
    return new Promise(resolve => {
      uni.canvasToTempFilePath({
        canvas: canvasEl,
        destWidth: imageWidth,
        destHeight: imageWidth * (4 / 5),
        fileType: 'jpg',
        quality: 1,
        success: async res => {
          const result = await uploadFn(res.tempFilePath);
          resolve(result);
        },
        fail: err => {
        }
      });
    });
  };
  defineExpose({ extendCanvas });
</script>
<style lang="scss" scoped>
  .cover {
    position: fixed;
    left: -100%;
  }
</style>
